package cn.lsc.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;


import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;

@Component
public class ZuulServlet extends ZuulFilter {
    @Override
    public String filterType() {//filter类型，可以通过父类查看返回值信息示例，例如：pre、post
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() { //是否执行run方法，true：执行/false：不执行
        //获取请求路径
        HttpServletRequest currentContext = RequestContext.getCurrentContext().getRequest();
        //获取上下文路劲
        String uri = currentContext.getRequestURI();
        // 3.判断是否包含login/register
        if(StringUtils.endsWithIgnoreCase(uri,"login")||StringUtils.endsWithIgnoreCase(uri,"register")){
            return false;
        }


        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 1.得到token
        String token = RequestContext.getCurrentContext().getRequest().getHeader("token");
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        // 对响应过去的数据设置格式和编码
        response.setContentType("application/json;charset=utf-8");
        //2 判断token是否为空
        if(StringUtils.isEmpty(token)){
            try {
                HashMap<String, Object> map = new HashMap<>();
                map.put("success",false);
                map.put("message","noLogin");
                PrintWriter writer= response.getWriter();
                String s = JSONObject.toJSONString(map);
                writer.write(s);
                //上面流程执行之后阻止程序继续filter
                RequestContext.getCurrentContext().setSendZuulResponse(false);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        // 如果你想要放行，那么此处你随便返回
        return null;
    }
}
